import 'base_generator.dart';

/// Widget组件生成器
class WidgetGenerator extends BaseGenerator {
  static void generate(String name, Map<String, dynamic> options) {
    if (!BaseGenerator.isValidName(name)) {
      BaseGenerator.printError('组件名称格式不正确: $name');
      return;
    }

    final String moduleName = options['module'] ?? '';
    final bool isStateful = options['stateful'] == true;
    final bool withController = options['with-controller'] == true;

    final String className = BaseGenerator.toPascalCase(name);
    final String fileName = BaseGenerator.toSnakeCase(name);
    final String modulePath = BaseGenerator.getModulePath(moduleName);
    
    // 创建组件目录
    final String widgetDir = moduleName.isEmpty ? 
        'lib/shared/widgets' : '$modulePath/presentation/widgets';
    BaseGenerator.createDirectoryIfNotExists(widgetDir);
    
    // 生成组件文件
    final String widgetPath = '$widgetDir/$fileName.dart';
    final String widgetContent = _generateWidgetContent(className, isStateful, withController);
    
    BaseGenerator.writeFile(widgetPath, widgetContent);
    
    // 如果需要创建控制器
    if (withController) {
      _createWidgetController(className, moduleName, widgetDir);
    }
    
    BaseGenerator.printSuccess('组件', className, widgetPath);
    
    if (withController) {
      print('📝 同时创建了对应的控制器');
    }
    
    _printUsageInstructions(className, isStateful, withController);
  }

  static String _generateWidgetContent(String className, bool isStateful, bool withController) {
    final String controllerName = '${className}Controller';
    final String controllerImport = withController ? 
        "import '${BaseGenerator.toSnakeCase(className)}_controller.dart';" : '';

    if (isStateful && !withController) {
      return _generateStatefulWidget(className);
    } else if (withController) {
      return _generateGetxWidget(className, controllerName, controllerImport);
    } else {
      return _generateStatelessWidget(className);
    }
  }

  static String _generateStatelessWidget(String className) {
    return BaseGenerator.generateFileHeader(
      className,
      '${className} - 无状态组件'
    ) + '''
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class $className extends StatelessWidget {
  final String? title;
  final VoidCallback? onTap;
  final Widget? child;
  final EdgeInsetsGeometry? padding;
  final Color? backgroundColor;
  final BorderRadius? borderRadius;

  const $className({
    Key? key,
    this.title,
    this.onTap,
    this.child,
    this.padding,
    this.backgroundColor,
    this.borderRadius,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: padding ?? EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: backgroundColor ?? Theme.of(context).cardColor,
        borderRadius: borderRadius ?? BorderRadius.circular(8.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: InkWell(
        onTap: onTap,
        borderRadius: borderRadius ?? BorderRadius.circular(8.r),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (title != null) ...[
              Text(
                title!,
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(height: 8.h),
            ],
            if (child != null) child!,
            if (child == null && title == null)
              Text(
                '$className组件',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[600],
                ),
              ),
          ],
        ),
      ),
    );
  }
}
''';
  }

  static String _generateStatefulWidget(String className) {
    return BaseGenerator.generateFileHeader(
      className,
      '${className} - 有状态组件'
    ) + '''
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class $className extends StatefulWidget {
  final String? title;
  final VoidCallback? onTap;
  final Widget? child;
  final EdgeInsetsGeometry? padding;
  final Color? backgroundColor;
  final BorderRadius? borderRadius;

  const $className({
    Key? key,
    this.title,
    this.onTap,
    this.child,
    this.padding,
    this.backgroundColor,
    this.borderRadius,
  }) : super(key: key);

  @override
  State<$className> createState() => _${className}State();
}

class _${className}State extends State<$className> 
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  bool _isPressed = false;

  @override
  void initState() {
    super.initState();
    _initAnimations();
  }

  void _initAnimations() {
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 150),
      vsync: this,
    );
    
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 0.95,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
  }

  void _onTapDown(TapDownDetails details) {
    setState(() => _isPressed = true);
    _animationController.forward();
  }

  void _onTapUp(TapUpDetails details) {
    setState(() => _isPressed = false);
    _animationController.reverse();
  }

  void _onTapCancel() {
    setState(() => _isPressed = false);
    _animationController.reverse();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _scaleAnimation,
      builder: (context, child) {
        return Transform.scale(
          scale: _scaleAnimation.value,
          child: Container(
            padding: widget.padding ?? EdgeInsets.all(16.w),
            decoration: BoxDecoration(
              color: widget.backgroundColor ?? Theme.of(context).cardColor,
              borderRadius: widget.borderRadius ?? BorderRadius.circular(8.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(_isPressed ? 0.15 : 0.1),
                  blurRadius: _isPressed ? 6 : 4,
                  offset: Offset(0, _isPressed ? 3 : 2),
                ),
              ],
            ),
            child: GestureDetector(
              onTapDown: _onTapDown,
              onTapUp: _onTapUp,
              onTapCancel: _onTapCancel,
              onTap: widget.onTap,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if (widget.title != null) ...[
                    Text(
                      widget.title!,
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 8.h),
                  ],
                  if (widget.child != null) widget.child!,
                  if (widget.child == null && widget.title == null)
                    Text(
                      '$className组件',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[600],
                      ),
                    ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }
}
''';
  }

  static String _generateGetxWidget(String className, String controllerName, String controllerImport) {
    return BaseGenerator.generateFileHeader(
      className,
      '${className} - 基于GetX的响应式组件'
    ) + '''
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
$controllerImport

class $className extends StatelessWidget {
  final String? title;
  final VoidCallback? onTap;
  final Widget? child;
  final EdgeInsetsGeometry? padding;
  final Color? backgroundColor;
  final BorderRadius? borderRadius;

  const $className({
    Key? key,
    this.title,
    this.onTap,
    this.child,
    this.padding,
    this.backgroundColor,
    this.borderRadius,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<$controllerName>(
      init: $controllerName(),
      builder: (controller) {
        return Obx(() => AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          padding: padding ?? EdgeInsets.all(16.w),
          decoration: BoxDecoration(
            color: backgroundColor ?? 
                (controller.isActive.value ? 
                    Theme.of(context).primaryColor.withOpacity(0.1) : 
                    Theme.of(context).cardColor),
            borderRadius: borderRadius ?? BorderRadius.circular(8.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(controller.isActive.value ? 0.15 : 0.1),
                blurRadius: controller.isActive.value ? 6 : 4,
                offset: Offset(0, controller.isActive.value ? 3 : 2),
              ),
            ],
          ),
          child: InkWell(
            onTap: () {
              controller.toggle();
              onTap?.call();
            },
            borderRadius: borderRadius ?? BorderRadius.circular(8.r),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        title ?? '$className组件',
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    if (controller.showBadge.value)
                      Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 8.w,
                          vertical: 4.h,
                        ),
                        decoration: BoxDecoration(
                          color: Theme.of(context).primaryColor,
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                        child: Text(
                          controller.badgeCount.value.toString(),
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 12.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                  ],
                ),
                if (child != null || controller.hasContent.value) ...[
                  SizedBox(height: 8.h),
                  child ?? Text(
                    '状态: \${controller.isActive.value ? "激活" : "未激活"}',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
                if (controller.showActions.value) ...[
                  SizedBox(height: 12.h),
                  Row(
                    children: [
                      ElevatedButton(
                        onPressed: controller.performAction,
                        style: ElevatedButton.styleFrom(
                          padding: EdgeInsets.symmetric(
                            horizontal: 16.w,
                            vertical: 8.h,
                          ),
                        ),
                        child: Text(
                          '执行操作',
                          style: TextStyle(fontSize: 12.sp),
                        ),
                      ),
                      SizedBox(width: 8.w),
                      TextButton(
                        onPressed: controller.reset,
                        child: Text(
                          '重置',
                          style: TextStyle(fontSize: 12.sp),
                        ),
                      ),
                    ],
                  ),
                ],
              ],
            ),
          ),
        ));
      },
    );
  }
}
''';
  }

  static void _createWidgetController(String className, String moduleName, String widgetDir) {
    final String controllerName = '${className}Controller';
    final String fileName = BaseGenerator.toSnakeCase(className);
    
    // 生成控制器文件
    final String controllerPath = '$widgetDir/${fileName}_controller.dart';
    final String controllerContent = _generateWidgetControllerContent(controllerName, className);
    
    BaseGenerator.writeFile(controllerPath, controllerContent);
  }

  static String _generateWidgetControllerContent(String controllerName, String className) {
    return BaseGenerator.generateFileHeader(
      controllerName,
      '${className}组件控制器'
    ) + '''
import 'package:get/get.dart';

class $controllerName extends GetxController {
  // 响应式状态变量
  final _isActive = false.obs;
  final _badgeCount = 0.obs;
  final _showBadge = false.obs;
  final _showActions = true.obs;
  final _hasContent = true.obs;
  
  // Getter
  RxBool get isActive => _isActive;
  RxInt get badgeCount => _badgeCount;
  RxBool get showBadge => _showBadge;
  RxBool get showActions => _showActions;
  RxBool get hasContent => _hasContent;

  @override
  void onInit() {
    super.onInit();
    _initController();
  }

  void _initController() {
    // 初始化组件状态
    _updateBadgeVisibility();
  }

  /// 切换激活状态
  void toggle() {
    _isActive.value = !_isActive.value;
    
    if (_isActive.value) {
      _incrementBadge();
    }
    
    update();
  }

  /// 设置激活状态
  void setActive(bool active) {
    _isActive.value = active;
    update();
  }

  /// 增加角标数量
  void _incrementBadge() {
    _badgeCount.value++;
    _updateBadgeVisibility();
  }

  /// 设置角标数量
  void setBadgeCount(int count) {
    _badgeCount.value = count;
    _updateBadgeVisibility();
  }

  /// 更新角标显示状态
  void _updateBadgeVisibility() {
    _showBadge.value = _badgeCount.value > 0;
  }

  /// 执行操作
  void performAction() {
    // 模拟执行某个操作
    Get.snackbar(
      '操作执行',
      '$className组件执行了操作',
      duration: const Duration(seconds: 2),
    );
    
    _incrementBadge();
  }

  /// 重置状态
  void reset() {
    _isActive.value = false;
    _badgeCount.value = 0;
    _updateBadgeVisibility();
    
    Get.snackbar(
      '重置完成',
      '$className组件状态已重置',
      duration: const Duration(seconds: 1),
    );
    
    update();
  }

  /// 设置内容显示状态
  void setContentVisibility(bool visible) {
    _hasContent.value = visible;
  }

  /// 设置操作按钮显示状态
  void setActionsVisibility(bool visible) {
    _showActions.value = visible;
  }

  /// 清除角标
  void clearBadge() {
    _badgeCount.value = 0;
    _updateBadgeVisibility();
  }

  @override
  void onClose() {
    // 清理资源
    super.onClose();
  }
}
''';
  }

  static void _printUsageInstructions(String className, bool isStateful, bool withController) {
    print('\n📋 使用说明:');
    
    print('1. 基础使用:');
    print('   $className(');
    print('     title: \'标题\',');
    print('     onTap: () => print(\'点击了组件\'),');
    print('     child: Text(\'自定义内容\'),');
    print('   )');
    
    print('');
    print('2. 自定义样式:');
    print('   $className(');
    print('     backgroundColor: Colors.blue.shade50,');
    print('     borderRadius: BorderRadius.circular(12),');
    print('     padding: EdgeInsets.all(20),');
    print('   )');

    if (withController) {
      print('');
      print('3. 控制器操作:');
      print('   final controller = Get.find<${className}Controller>();');
      print('   controller.setActive(true);');
      print('   controller.setBadgeCount(5);');
      print('   controller.performAction();');
    }

    if (isStateful) {
      print('');
      print('4. 动画效果:');
      print('   该组件包含点击动画和阴影效果');
    }

    print('');
    print('5. 在页面中使用:');
    print('   Column(');
    print('     children: [');
    print('       $className(title: \'组件1\'),');
    print('       SizedBox(height: 16),');
    print('       $className(title: \'组件2\'),');
    print('     ],');
    print('   )');
  }
}
''';
  }
}